package org.tooyoung.fourone.user;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.tooyoung.fourone.BaseFragment;
import org.tooyoung.fourone.R;
import org.tooyoung.fourone.user.activity.LoginActivity;
import org.tooyoung.fourone.user.activity.RegisterActivity;
import org.tooyoung.fourone.user.adapters.MyListviewAdapter;
import org.tooyoung.fourone.user.model.UserImformation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserFragment extends BaseFragment implements View.OnClickListener {
    protected static Uri tempUri;
    private ImageView iv_personal_icon;
    private ImageView image_icon;
    private String mUsername;
    private ArrayList<String> mList;
    private String mPrivince;
    private String mAddressDetail;
    private String mPhoneNumber;
    private String mEmailAddress;
    public static boolean isCompelete;
    private ListView mListView;
    private MyListviewAdapter mAdapter;
    public static final int CHOOSE_PICTURE = 0;
    public static final int TAKE_PICTURE = 1;
    private File mTargetFile;

    public UserFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Bmob.initialize(getContext(), "1c20f8eef3a087e65f6e1012ac4307f4");
        View ret = null;
        ret = inflater.inflate(R.layout.fragment_user,container,false);
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        mUsername = bundle.getString("username");
        Toolbar toolbar = (Toolbar) ret.findViewById(R.id.userfragment_toolbar);
        AppCompatActivity compatActivity = (AppCompatActivity) getActivity();
        compatActivity.setSupportActionBar(toolbar);
        ActionBar actionBar = compatActivity.getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        TextView textView = (TextView) ret.findViewById(R.id.frgament_username);
        textView.setText(mUsername);
        image_icon = ((ImageView) ret.findViewById(R.id.iv_personal_icon));
        mListView = (ListView) ret.findViewById(R.id.fragment_list);
        TextView btn_live = (TextView) ret.findViewById(R.id.btn_p1_live);
        TextView btn_map = (TextView) ret.findViewById(R.id.btn_p2_map);
        TextView btn_chat = (TextView) ret.findViewById(R.id.btn_p3_chat);
        TextView btn_other = (TextView) ret.findViewById(R.id.btn_p4_other);
        btn_live.setOnClickListener(this);
        btn_map.setOnClickListener(this);
        btn_chat.setOnClickListener(this);
        btn_other.setOnClickListener(this);
        image_icon.setOnClickListener(this);
        mList = new ArrayList<>();
        mAdapter = new MyListviewAdapter(getContext(),mList);
        addInformation();
        return ret;
    }

    private void addInformation() {
        BmobQuery query = new BmobQuery("UserImformation");
        query.addWhereEqualTo("username",mUsername);
        query.findObjectsByTable(new QueryListener<JSONArray>() {
            @Override
            public void done(JSONArray jsonArray, BmobException e) {
                try {
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    mPrivince = jsonObject.getString("privince");
                    mAddressDetail = jsonObject.getString("addressDetail");
                    mPhoneNumber = jsonObject.getString("phoneNumber");
                    mEmailAddress = jsonObject.getString("emailAddress");
                    mList.add(mUsername);
                    mList.add(mPrivince);
                    mList.add(mAddressDetail);
                    mList.add(mPhoneNumber);
                    mList.add(mEmailAddress);
                    mListView.setAdapter(mAdapter);
                    mAdapter.notifyDataSetChanged();
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }

            }
        });

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.user_menu,menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId){
            case R.id.user_menu_exit:
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.user_menu_help:
                Toast.makeText(getContext(), "帮助", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }

    @Override
    public String getTitle() {
        return "用户";
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.iv_personal_icon:
                showChoosePicDialog();
                break;
            case R.id.btn_p1_live:
                break;
            case R.id.btn_p2_map:
                break;
            case R.id.btn_p3_chat:
                break;
            case R.id.btn_p4_other:
                break;
        }

    }
    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("设置头像");
        String[] items = { "选择本地照片", "拍照" };
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("image/*");
                        startActivityForResult(intent, 999);
                        break;
                    case TAKE_PICTURE: // 拍照
                        Intent intent_1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        // 使用 EXTRA_OUTPUT 指定 Uri 位置，可以把大尺寸原图保存到 Uri 指定的位置

                        String state = Environment.getExternalStorageState();
                        File dir = getActivity().getFilesDir();
                        if (state.equals(Environment.MEDIA_MOUNTED)) {
                            dir = Environment.getExternalStorageDirectory();
                        }

                        if (!dir.exists()) {
                            dir.mkdirs();
                        }

                        mTargetFile = new File(dir, "img-" + System.currentTimeMillis() + ".jpg");
                        Uri uri = Uri.fromFile(mTargetFile);
                        intent_1.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        startActivityForResult(intent_1, 998);
                        break;
                }
            }
        });
        builder.create().show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("MainActivity", "onActivityResult:" +data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 998) {
                //拍照
                // Bitmap bitmap = BitmapFactory.decodeFile(mTargetFile.getAbsolutePath());
                //Log.d("MianActivity", "onActivityResult:" + mTargetFile.getAbsoluteFile().toString());
                Uri uri = Uri.fromFile(mTargetFile);
                startPhotoZoom(uri);
            } else if (requestCode == 999) {
                //本地
                // Log.d("MainActivity", "onActivityResult:"+data.getData());
                //uri上传服务器的地址
                startPhotoZoom(data.getData());
            } else if (requestCode == 1000) {
                setImageToView(data);
            }
        }
    }
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            image_icon.setImageBitmap(photo);
        }
    }

    protected void startPhotoZoom(Uri uri) {
        Log.d("UUUU", "startPhotoZoom:"+uri);
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 1000);
    }
}

